package com.ctsi.security.service;

import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.response.Page;
import com.ctsi.framework.mybatis.support.MybatisGenericDao;
import com.ctsi.security.ISecurity;
import com.ctsi.security.PartySrole;
import com.ctsi.security.domain.SRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.*;

@Repository
public class SecSRoleService implements PartySrole {
    private final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SecSRoleService.class);
    @Autowired
    private ISecurity security;
    @Autowired
    private MybatisGenericDao dao;

    private String dataObjectType = "sysModule";
    private String action = "SELECT";


    public MybatisGenericDao getDao() {
        return dao;
    }


    public void setDao(MybatisGenericDao dao) {
        this.dao = dao;
    }


    /**
     * 分页查询权限角色数据
     *
     * @param pageSize
     * @param startIndex
     * @return
     */
    private Page queryRole(int pageSize, int startIndex) {

        return dao.queryPage(SRole.class.getName() + ".selectByMap", Collections.EMPTY_MAP, startIndex, pageSize);
    }


    @Override
    public Page queryRole(String userLogin, String dataObjectType, String action, int pageSize, int startIndex) {
        return queryRoleByName(userLogin, dataObjectType, action, pageSize, startIndex, null);
    }

    @Override
    public Page queryRoleByName(String userLogin, String dataObjectType, String action, int pageSize, int startIndex, String roleName) {
        Map<String, Object> params = new HashMap<String, Object>();
        if (UtilValidate.isNotEmpty(roleName)) {
            if (!roleName.startsWith("%")) {
                roleName = "%" + roleName + "%";
            }
            params.put("roleName", roleName);
        }

        return this.queryRole(userLogin, dataObjectType, action, pageSize, startIndex, params);

    }


    @Override
    public Page queryRole(String userLogin, String dataObjectType, String action, int pageSize, int startIndex, Map<String, Object> params) {
        if (params == null) {
            params = new HashMap<>();
        }
        if (security.isControl(userLogin, dataObjectType, action)) {
            List<String> dataObjectIds = security.getDataObjectIds(userLogin, dataObjectType, action);
            if (UtilValidate.isEmpty(dataObjectIds)) {
                return new Page<SRole>();
            }
            if (dataObjectIds.size() == 1) {
                params.put("dataObjectId", dataObjectIds.get(0));
            } else {
                // >1
                params.put("dataObjectIds", dataObjectIds);
            }
        }
        return dao.queryPage(SRole.class.getName() + ".queryRoleByDataPer", params, startIndex, pageSize);
    }


    @Override
    public List<SRole> getSRolesByPartyId(String userLoginId, String dataObjectType, String action, String partyId) {
        List<SRole> result = new ArrayList<SRole>();// 返回结果
        Map<String, Object> params = new HashMap<String, Object>();// 查询参数
        params.put("partyId", partyId);
        // 是否控制数据权限
        if (!security.isControl(userLoginId, dataObjectType, action)) {// 不控制数据权限
            logger.debug("{} is not controlled for {}", userLoginId, dataObjectType);
        } else {// 控制数据权限
            List<String> dataObjectIds = security.getDataObjectIds(userLoginId, dataObjectType, action);
            // 是否为空
            if (UtilValidate.isNotEmpty(dataObjectIds)) {// 不为空
                logger.debug("{} is controlled for {},the dataObjectIds are {}", userLoginId, dataObjectType, dataObjectIds);
                if (dataObjectIds.size() == 1) {// 等于1，避免IN操作
                    params.put("dataObjectId", dataObjectIds.get(0));
                } else {// 大于1，使用IN操作
                    params.put("dataObjectIds", dataObjectIds);
                }
            } else {// 为空
                logger.debug("{} is controlled for {},but dataObjectIds are null", userLoginId, dataObjectType);
                return result;
            }
        }
        result = (List<SRole>) dao.queryForList(SRole.class.getName().concat(".querySRoleByPartyId"), params);
        return result;
    }

    @Override
    public ISecurity getSecurity() {
        return security;
    }

    public void setSecurity(ISecurity security) {
        this.security = security;
    }

    @Override
    public Page<Map<String, Object>> queryPersonSec(String userLoginId, String loginId, String name, int startIndex, int pageSize) {
        Map<String, Object> param = new HashMap<String, Object>();
        if (security.isControl(userLoginId, dataObjectType, action)) {
            List<String> dataObjectIds = security.getDataObjectIds(userLoginId, dataObjectType, action);
            param.put("DATAOBJECT", dataObjectIds);
        }
        if (UtilValidate.isNotEmpty(name)) {
            param.put("NAME", name);
        }
        param.put("LOGINID", loginId);
        return dao.queryPage(SRole.class.getName().concat(".queryPersonSec"), param, startIndex, pageSize);
    }


    @Override
    public Page<SRole> getSRolesByLoginId(String userLoginId, String dataObjectType, String action, String loginId, Map<String, Object> conds, int startIndex) {

        Map<String, Object> params = new HashMap<String, Object>();// 查询参数
        params.put("loginId", loginId);
        if (UtilValidate.isNotEmpty(conds)) {
            params.putAll(conds);
        }
        if (UtilValidate.isNotEmpty(userLoginId) && UtilValidate.isNotEmpty(dataObjectType)) {
            // 是否控制数据权限
            if (!security.isControl(userLoginId, dataObjectType, action)) {// 不控制数据权限
                logger.debug("{} is not controlled for {}", userLoginId, dataObjectType);
            } else {// 控制数据权限
                List<String> dataObjectIds = security.getDataObjectIds(userLoginId, dataObjectType, action);
                // 是否为空
                if (UtilValidate.isNotEmpty(dataObjectIds)) {// 不为空
                    logger.debug("{} is controlled for {},the dataObjectIds are {}", userLoginId, dataObjectType, dataObjectIds);
                    if (dataObjectIds.size() == 1) {// 等于1，避免IN操作
                        params.put("dataObjectId", dataObjectIds.get(0));
                    } else {// 大于1，使用IN操作
                        params.put("dataObjectIds", dataObjectIds);
                    }
                } else {// 为空
                    logger.debug("{} is controlled for {},but dataObjectIds are null", userLoginId, dataObjectType);
                    return new Page<SRole>();
                }
            }
        }
        return dao.queryPage(SRole.class.getName().concat(".querySRoleByPartyId"), params, startIndex, 70);

    }

    /**
     * 不带权限的根据用户登录Id查找相应角色
     *
     * @param loginId
     * @param startIndex
     * @return
     */
    public Page<SRole> getSRolesByLoginId(String loginId, Map<String, Object> conds, int startIndex) {
        return getSRolesByLoginId(null, "", "all", loginId, conds, startIndex);

    }

    @Override
    public List<SRole> findAllSroleByPartyId(String partyId, String roleType) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("partyId", partyId);
        param.put("roleType", roleType);
        return (List<SRole>) dao.queryForList(SRole.class.getName() + ".querySRoleByPartyId", param);

    }


}
